package com.ruoyi.business.webapi.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.mysqldump.domain.BizProjectBackup;
import com.ruoyi.mysqldump.domain.BizProjectInfo;
import com.ruoyi.mysqldump.service.IBizProjectBackupService;
import com.ruoyi.mysqldump.service.IBizProjectInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 项目管理定时任务
 *
 * @author Tellsea
 * @date 2022/02/11
 */
@Slf4j
@Component("bizProjectInfoTask")
public class BizProjectInfoTask {

	@Autowired
	private IBizProjectInfoService projectInfoService;
	@Autowired
	private IBizProjectBackupService projectBackupService;

	/**
	 * 备份定时任务
	 */
	public void handleBackup() {
		log.info("-------------------------------------------------------------- 开始执行备份");
		List<BizProjectInfo> list = projectInfoService.list(new LambdaQueryWrapper<BizProjectInfo>().eq(BizProjectInfo::getIsBackup, 1));
		for (BizProjectInfo projectInfo : list) {
			try {
				// String mysqlDumpCommand = "mysqldump --host 127.0.0.1 --port 3306 -u root -p123456 --databases ry-vue > D:/bak.sql";
				StringBuilder mysqlDumpCommand = new StringBuilder();
				mysqlDumpCommand.append("mysqldump ");
				mysqlDumpCommand.append(" --host ").append(projectInfo.getDbHost());
				mysqlDumpCommand.append(" --port ").append(projectInfo.getDbPort());
				mysqlDumpCommand.append(" -u ").append(projectInfo.getDbUser());
				mysqlDumpCommand.append(" -p").append(projectInfo.getDbPassword());
				mysqlDumpCommand.append(" --databases ").append(projectInfo.getDbName());
				mysqlDumpCommand.append(" > ");
				// 文件夹
				String dateFolder = DateUtil.format(DateUtil.parse(DateUtil.now()), "/yyyy/MM/dd/");
				// 文件名称
				String fileName = DateUtil.format(DateUtil.parse(DateUtil.now()), "yyyy-MM-dd-HH-mm-ss-") + projectInfo.getDbName() + ".sql";
				// 根目录
				String rootPath = "D:/Workspace/ZhhyWorkspace/mysqldump/mysqldump-service/uploadFile";
				// 相对路径
				String targetPath = "/mysqldump/" + projectInfo.getDbName() + dateFolder;
				// 绝对路径
				String filePath = rootPath + targetPath;
				// 访问路径（存数据库）
				String backupUrl = targetPath + fileName;
				File file = new File(filePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				mysqlDumpCommand.append(filePath).append(fileName);
				log.info("【执行语句】：{}", mysqlDumpCommand.toString());
				BizProjectBackup projectBackup = new BizProjectBackup()
					.setProjectId(projectInfo.getId())
					.setUserId(projectInfo.getUserId())
					.setDbName(projectInfo.getDbName())
					.setDbHost(projectInfo.getDbHost())
					.setDbPort(projectInfo.getDbPort())
					.setDbUser(projectInfo.getDbUser())
					.setDbPassword(projectInfo.getDbPassword())
					.setBackupCommand(mysqlDumpCommand.toString())
					.setBackupUrl(backupUrl)
					.setBackupStatus(1L);
				projectBackupService.save(projectBackup);
				String os = System.getProperty("os.name");
				if (os.toLowerCase().startsWith("win")) {
					Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", mysqlDumpCommand.toString()});
					process.waitFor();
					projectBackup.setBackupStatus(Long.valueOf(2));
					projectBackupService.updateById(projectBackup);
				} else if (os.toLowerCase().startsWith("linux")) {
					Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", mysqlDumpCommand.toString()});
					process.waitFor();
					projectBackup.setBackupStatus(Long.valueOf(2));
					projectBackupService.updateById(projectBackup);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		log.info("--------------------------------------------------------------  备份执行完成");
	}
}
